package com.ineatconseil.yougo.components;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.annotations.BeginRender;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.ioc.annotations.Inject;

import com.ineatconseil.yougo.dto.RequestTypeDto;
import com.ineatconseil.yougo.exceptions.RestServiceException;
import com.ineatconseil.yougo.services.rest.RestPath;
import com.ineatconseil.yougo.services.rest.RestServiceInvoker;

/**
 * Component use to convert the request type.
 * 
 * @author johanblo
 * 
 */
public class RequestTypeLabel {

	private static Map<Long, RequestTypeDto> types = new HashMap<Long, RequestTypeDto>();

	@Inject
	private RestServiceInvoker restServiceInvoker;

	@Parameter
	private long value = 0;

	@BeginRender
	void renderMessage(MarkupWriter writer) {

		try {

			if (value != 0) {

				if (!types.containsKey(value)) {
					types.put(value, getRequestType());
				}

				RequestTypeDto reqType = types.get(value);

				if (reqType != null) {
					writer.write(reqType.getDescription());
				}

			}

		} catch (RestServiceException e) {
			writer.write("");
		}

	}

	private RequestTypeDto getRequestType() throws RestServiceException {

		List<RestPath> paths = new ArrayList<RestPath>();
		paths.add(new RestPath("request-types", String.valueOf(value)));

		return restServiceInvoker.call(paths, RequestTypeDto.class);

	}

}